package com.hmdp.utils;

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;


public class MailUtils {
    // QQ邮箱SMTP服务器地址
    private static final String SMTP_HOST = "smtp.qq.com";

    // 发件人邮箱地址（你的QQ邮箱）
    private static final String FROM_EMAIL = "1971667429@qq.com";

    // 授权码（不是QQ密码）
    private static final String AUTH_CODE = "ovntwjipqvqybfab";  // 替换为你的授权码

    public static void sendEmail(String to, String subject, String content) {
        // 设置邮件会话属性
        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.port", "465");

        // 创建认证信息
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(FROM_EMAIL, AUTH_CODE);
            }
        };

        // 获取Session对象
        Session session = Session.getInstance(props, authenticator);

        try {
            // 创建邮件对象
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(FROM_EMAIL));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(subject);

            // 设置邮件内容（支持HTML格式）
            message.setContent(content, "text/html;charset=UTF-8");

            // 发送邮件
            Transport.send(message);
            System.out.println("邮件发送成功！");
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        sendEmail(
                "1971667429@qq.com",
                "测试邮件主题",
                "<h1>这是测试邮件内容，支持HTML哦！</h1>"
        );
    }
}